package com.jhd.fuzhou.util;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.service.ProcessService;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.vo.ActivityVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.ProInstance;
import com.jhd.fuzhou.vo.Process;
import com.jhd.fuzhou.vo.ReceiveReportVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*开启流程*/
public class ReceiptProcess {
    public static void getProInstanceId(FuzhouApplication application, String id,ReceiveReportVo receiveReportVo,String message,String assignee, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("businessKey",id);
        Call<JsonForResult> jsonForResultCall = vs.getProInstanceId(application.getAccessToken(),application.getUserName(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            ProInstance proInstance= JSON.parseObject(jsonForResult.getData().toString(), ProInstance.class);
                            list(application,proInstance.getProcessInstanceId(),receiveReportVo,message,assignee,context);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void list(FuzhouApplication application, String procInstId,ReceiveReportVo receiveReportVo,String message,String assignee,Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("procInstId",procInstId);
        Call<JsonForResult> jsonForResultCall = vs.list(application.getAccessToken(),application.getUserName(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            List<Process> processList = JSON.parseArray(jsonForResult.getData().toString(), Process.class);
                            if(processList!=null){
                                if(StringUtil.isNullOrEmpty(assignee)){//是驳回
                                    for(int i=processList.size()-1;i>=0;i--){
                                        if(processList.get(i).getTaskName().equals(receiveReportVo.getProgress())){
                                            backNodes(application,receiveReportVo,message,context);
                                            break;
                                        }
                                    }
                                }else{
                                    for (Process process1 : processList) {
                                        if(process1.getTaskName().equals(receiveReportVo.getProgress())){
                                            completeByAssign(application,receiveReportVo,assignee,message,context);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public static void backNodes(FuzhouApplication application, ReceiveReportVo receiveReportVo, String message, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("taskId",receiveReportVo.getTaskId());
        Call<JsonForResult> jsonForResultCall = vs.backNodes(application.getAccessToken(),application.getUserName(),params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        List<ActivityVo> activityVoList =JSON.parseArray(jsonForResult.getData().toString(), ActivityVo.class);
                        if(activityVoList!=null){
                            for (ActivityVo activityVo : activityVoList) {
                                if("拟稿".equals(activityVo.getActivityName())){
                                    back(application,receiveReportVo, activityVo.getActivityId(),message,context);
                                    break;
                                }
                            }
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public static void back(FuzhouApplication application,ReceiveReportVo receiveReportVo,String targetActivityId,String message, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);

        Map<String, String> params = ParamsMapUtil.getInstance("taskId",receiveReportVo.getTaskId()).addParam("targetActivityId",targetActivityId).addParam("backMessage",message);
        /*Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("targetActivityId",targetActivityId);
        params.put("taskId",taskId);
        if(!StringUtil.isNullOrEmpty(message))params.put("backMessage",message);*/
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.back(application.getAccessToken(),application.getUserName(),params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            AddReadPerson.postMessage(application,context,receiveReportVo,jsonForResult.getData().toString());
                        }
                        application.exitTask();
                        CustomToast.showText(context,receiveReportVo.getProgress()+"驳回成功!",3000,0,0).show();
                        /*Intent intent = new Intent();
                        intent.putExtra("position","2");
                        ((Activity)context).setResult(RESULT_OK, intent);
                        ((Activity)context).finish();*/
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }


    public static void completeByAssign(FuzhouApplication application,ReceiveReportVo receiveReportVo,String assignee,String message, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("assignees",assignee);
        params.put("taskId",receiveReportVo.getTaskId());
        if(!StringUtil.isNullOrEmpty(message))params.put("message",message);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        String json=JSON.toJSONString(params);
        Call<JsonForResult> jsonForResultCall = vs.completeByAssign(application.getAccessToken(),application.getUserName(),requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(!"主管领导审核".equals(receiveReportVo.getProgress())){
                            AddReadPerson.postMessage(application,context,receiveReportVo,assignee);
                        }
                        application.exitTask();
                        CustomToast.showText(context,receiveReportVo.getProgress()+"成功!",3000,0,0).show();
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

}
